<?php

namespace Service;

/**
 * 统一返回服务
 * Class ResponseService
 * @package Service
 */
class ResponseService
{

    function __construct()
    {
    }

    /**
     * json返回
     * @param string $code
     * @param string $msg
     * @param array $data
     * @param array $header
     * @param string $debugMsg
     */
    public static function json($code='', $msg='', $data = [], $header = [], $debugMsg='')
    {
        \Yaf\Dispatcher::getInstance()->disableView();
        $ret['code'] = (string)$code;
        $ret['msg'] = $msg;
        $ret['debugMsg'] = $debugMsg;
        if(is_array($data)){
            $ret = array_merge($ret,$data);
        }else{
            $ret['data'] = $data;
        }
        if (!empty($header)){
            foreach ($header as $name => $val) {
                if (is_null($val)) {
                    header($name);
                } else {
                    header($name . ':' . $val);
                }
            }
        }
        $result = json_encode($ret,JSON_UNESCAPED_UNICODE);
        if (!$result){
            exit(json_encode(['code'=>10088,'msg'=>'返回数据编码失败，请重试','debugMsg'=>'返回集json编码失败']));
        }
        exit($result);
    }

    /**
     * 页面渲染
     * @param $controller
     * @param array $data
     * @return mixed
     */
    public static function view($controller, $data = [])
    {
        return $controller->getView()->assign($data);
    }

}